package com.qianfeng.lingshijia;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.List;

import adapter.OtherGoodsSingleAdapter;
import entity.GoodsEntity;
import entity.SchoolMartketDetailEntity;
import utils.Constants;
import utils.DownloadUtils;

/**
 * 店铺商品详情显示页面
 */
@ContentView(R.layout.activity_school_market_detail)
public class SchoolMarketDetailActivity extends Activity implements
        AdapterView.OnItemClickListener, AbsListView.OnScrollListener, RadioGroup.OnCheckedChangeListener {

    @OnClick(R.id.rlBackToSMList)
    public void OnClick(View v) {
        finish();
    }

    @ViewInject(R.id.lvGoodsDetail)
    private ListView lvGoodsDetail;

    @ViewInject(R.id.tvMarketNameDetail)
    private TextView tvMarketNameDetail;//店铺名称

    @ViewInject(R.id.tvMarketMessage)
    private TextView tvMarketMessage;//商品信息

    @ViewInject(R.id.rgGoodsDetail)
    private RadioGroup rgGoodsDetail;

    private int schoolMarketId;//记录店铺的id
    private String schoolMarketName;//记录店铺的名字

    List<GoodsEntity> geList;

    List<String> stringList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);

        //清空显示的信息
        tvMarketNameDetail.setText("");
        tvMarketMessage.setText("");

        stringList = new ArrayList<>();
        stringList.add(getString(R.string.combincation_sell));
        stringList.add(getString(R.string.allay));
        stringList.add(getString(R.string.satisfy_desires));
        stringList.add(getString(R.string.quench));
        stringList.add(getString(R.string.treasure_box));

        rgGoodsDetail.setOnCheckedChangeListener(this);

        schoolMarketId = getIntent().getIntExtra("schoolMarketId", -1);
        if (schoolMarketId != -1) {
            DownloadUtils.getJson(Constants.URL.SCHOOL_MARKET_DETAIL_URL + schoolMarketId,
                    new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            SchoolMartketDetailEntity smdEntity = new Gson().fromJson(responseInfo.result, SchoolMartketDetailEntity.class);
                            //数据获取

                            //获取并设置店铺名字
                            schoolMarketName = smdEntity.getData().getSellerShop().getShopName();
                            tvMarketNameDetail.setText(schoolMarketName);

                            //获取并设置店铺信息
                            tvMarketMessage.setText(smdEntity.getData().getSellerShop().getGreet());
                            //解析实体类中的数据
                            geList = new ArrayList<>();

                            //设置组合特卖
                            List<SchoolMartketDetailEntity.DataEntity.CombinationListEntity> cList = smdEntity.getData().getCombinationList();
                            if (cList != null && cList.size() != 0) {
                                try {
                                    for (int i = 0; i < cList.size(); i++)
                                        getDataToList(cList.get(i));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                Log.e("SchoolMarketDetailActivity", "onSuccess:组合特卖为基数或者为空");
                            }

                            //设置商品列表
                            List<SchoolMartketDetailEntity.DataEntity.PtListEntity> ptList = smdEntity.getData().getPtList();
                            for (int i = 0; i < ptList.size(); i++) {
                                GoodsEntity title = new GoodsEntity();
                                List<SchoolMartketDetailEntity.DataEntity.PtListEntity.PListEntity> pList = ptList.get(i).getPList();
                                setDataToGeList(title, pList, stringList.get(ptList.get(i).getCateType()));
                            }
                            lvGoodsDetail.setAdapter(new OtherGoodsSingleAdapter(SchoolMarketDetailActivity.this, geList, tvMarketNameDetail.getText().toString()));
                            lvGoodsDetail.setOnItemClickListener(SchoolMarketDetailActivity.this);//ListView列表点击事件
                            lvGoodsDetail.setOnScrollListener(SchoolMarketDetailActivity.this);
                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                            Toast.makeText(SchoolMarketDetailActivity.this, "亲，网络不给力啊！请稍后再试", Toast.LENGTH_LONG).show();
                        }
                    });
        } else {
            Log.e("SchoolMarketDetailActivity", "onCreate() 参数传递错误，没有传递正确的学校店铺id");
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    /**
     * ViewGroup的选择监听器
     *
     * @param group     点击的ViewGroup
     * @param checkedId 点击的ID
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int postion = -1;
        switch (checkedId) {
            case R.id.rb_allay:
                postion = findPostionByName(getString(R.string.combincation_sell));
                if (postion == -1) {
                    postion = findPostionByName(getString(R.string.allay));
                }
                break;
            case R.id.rb_satisfy_desires:
                postion = findPostionByName(getString(R.string.satisfy_desires));
                break;
            case R.id.rb_quench:
                postion = findPostionByName(getString(R.string.quench));
                break;
            case R.id.rb_treasure_box:
                postion = findPostionByName(getString(R.string.treasure_box));
                break;
        }
        if (postion != -1) {
            lvGoodsDetail.setSelection(postion);
        }
    }

    /**
     * 通过名字找到标题的位置
     *
     * @param name
     * @return
     */
    private int findPostionByName(String name) {
        if (name != null) {
            for (int i = 0; i < geList.size(); i++) {
                if (geList.get(i).getType() == 0 && name.equals(geList.get(i).getGoodsName())) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * ListView滚动时的监听器
     *
     * @param view             滚动的ListView
     * @param firstVisibleItem 屏幕显示的第一个view在list的位置
     * @param visibleItemCount 屏幕可以看到的list数量
     * @param totalItemCount   list的列数
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        GoodsEntity firstEntity = geList.get(firstVisibleItem);
        if (firstEntity.getType() == 0) {
            for (int i = 0; i < stringList.size(); i++) {
                if (stringList.get(i).equals(firstEntity.getGoodsName())) {
                    switch (i) {
                        case 0:
                        case 1:
                            ((RadioButton) rgGoodsDetail.findViewById(R.id.rb_allay)).setChecked(true);
                            break;
                        case 2:
                            ((RadioButton) rgGoodsDetail.findViewById(R.id.rb_satisfy_desires)).setChecked(true);
                            break;
                        case 3:
                            ((RadioButton) rgGoodsDetail.findViewById(R.id.rb_quench)).setChecked(true);
                            break;
                        case 4:
                            ((RadioButton) rgGoodsDetail.findViewById(R.id.rb_treasure_box)).setChecked(true);
                            break;
                    }
                }
            }
        }
    }

    /**
     * 把数据加载到List列表中，类型为2
     *
     * @param title 商品实体类
     * @param pList 商品列表
     * @param t     标题字符串
     */
    private void setDataToGeList(GoodsEntity title, List<SchoolMartketDetailEntity.DataEntity.PtListEntity.PListEntity> pList
            , String t) {
        if (pList.size() != 0) {
            title.setGoodsName(t);
            geList.add(title);
            for (int j = 0; j < pList.size(); j++) {
                GoodsEntity entity1 = new GoodsEntity();
                entity1.setSellerId(pList.get(j).getSellerId());
                entity1.setStock(pList.get(j).getStock());
                entity1.setIvImageUrl(pList.get(j).getImgUrl());
                entity1.setPrice(pList.get(j).getPriceStr());
                entity1.setGoodsName(pList.get(j).getTitle());
                entity1.setType(2);
                entity1.setSalesVolume(pList.get(j).getSalesVolume());
                entity1.setProductId(pList.get(j).getId());
                if (getString(R.string.treasure_box).equals(t)) {
                    entity1.setGoodsType(6);
                } else {
                    entity1.setGoodsType(4);
                }
                geList.add(entity1);
            }
        }
    }

    /**
     * 把数据加载到List列表中，类型为1
     *
     * @param cEntity 需要加入列表的类
     * @return 是否加载到组合特卖的列表
     * @throws Exception
     */
    private boolean getDataToList(SchoolMartketDetailEntity.DataEntity.CombinationListEntity cEntity) throws Exception {
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setType(1);
        goodsEntity.setSellerId(cEntity.getSellerId());
        goodsEntity.setStock(cEntity.getStock());
        goodsEntity.setPrice(cEntity.getPriceStr());

        List<SchoolMartketDetailEntity.DataEntity.CombinationListEntity.CombProductsEntity> cpList = cEntity.getCombProducts();
        if (cpList != null && cpList.size() != 0 && cpList.size() % 2 == 0) {
            //设置特卖标题
            GoodsEntity cTitle = new GoodsEntity();
            cTitle.setGoodsName(getString(R.string.combincation_sell));
            geList.add(cTitle);

            //第一个的商品名称
            goodsEntity.setIvImageUrl(cpList.get(0).getImgUrl());
            goodsEntity.setGoodsName(cpList.get(0).getTitle());

            //第二个的商品名称
            goodsEntity.setIvOtherImageUrl(cpList.get(1).getImgUrl());
            goodsEntity.setTvOtherGoodsName(cpList.get(1).getTitle());

            geList.add(goodsEntity);
            return true;
        } else {
            throw new Exception("错误，输入的组合特卖不是2的倍数或者为0或者为空。");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.e("===========", "id: "+view.getId()+"=========="+id);
        if (geList.get(position).getType() == 2) {
            Intent intent = new Intent(this, GoodsDetailPageActivity.class);
            intent.putExtra("productId", geList.get(position).getProductId());
            intent.putExtra("sellerId", geList.get(position).getSellerId());
            intent.putExtra("goodsType", geList.get(position).getGoodsType());
            startActivity(intent);
        }
    }


}
